//
//  ImageViewExtension.swift
//  WineComing
//
//  Created by xiaozhi on 15/7/2.
//  Copyright (c) 2015年 xiaozhi. All rights reserved.
//

import UIKit
extension UIImageView{
    
}
public class  XZImageView:UIImageView{
    var existAndPath = (false,"")
    let session:NSURLSession
    var imageLoadFinished:((UIImage,CGSize)->Void)?
    let constWidth = UIScreen.mainScreen().bounds.size.width
    public let delegate:ImageSessionDelegate
    private func setFinisheClosure(){
        delegate.finishedClosure = {[weak self] image,downloadTask in
            if(downloadTask.taskDescription==self?.existAndPath.1){
                dispatch_async(dispatch_get_main_queue()){
                    if self?.imageLoadFinished != nil{
                        let height = image.size.height*self!.constWidth/image.size.width
                        self?.imageLoadFinished!(image,CGSizeMake(self!.constWidth, height))
                    }
                    self?.image = image
                }
            }
            else{
                print("not current image")
            }
        }
    }
    override init(frame: CGRect) {
        delegate = ImageSessionDelegate()
        session =  NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate:delegate,delegateQueue: nil)
        super.init(frame: frame)
        self.setFinisheClosure()
    }
    public required  init?(coder aDecoder: NSCoder){
        delegate = ImageSessionDelegate()
        session =  NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate:delegate,delegateQueue: nil)
        super.init(coder: aDecoder)
        self.setFinisheClosure()
    }
    deinit{
        session.invalidateAndCancel()
        print("xzImageView deinit")
    }
    public final class ImageSessionDelegate:NSObject,NSURLSessionDownloadDelegate{
    public var finishedClosure:((UIImage,NSURLSessionDownloadTask)->Void)?
      public   func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL){
            //重要！下载完成后数据是否有效
        if let data = NSData(contentsOfURL: location){
            if let image = UIImage(data: data){
                data.writeToFile(downloadTask.taskDescription!, atomically:true)
                finishedClosure!(image,downloadTask)
            }
        }
        }
      public   func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?){
            if((error) != nil){
            }
        }
       public  func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64){
            //        println("compelete percent :\(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite))")
        }
    }
}
extension XZImageView{
    func setImageWithUrl(urlString:String,defaultImage:UIImage?){
        //根据url查看cache下imageCache是否已经存在该图片
        if urlString == "" {
            self.image = defaultImage
            return
        }

         existAndPath = Common.imageFileExistInCache(urlString)
        if(existAndPath.0){
            //存在则直接设置
            if let image = UIImage(contentsOfFile: existAndPath.1){
                if self.imageLoadFinished != nil{
                    let height = image.size.height*self.constWidth/image.size.width
                    self.imageLoadFinished!(image,CGSizeMake(self.constWidth, height))
                }
                self.image = image
            }
            else{
                if let image = defaultImage{
                    self.image = image
                }
            }
        }
            //不存在则需要下载
        else{
            if let image = defaultImage{
                self.image = image
            }
            var urlstr = urlString as NSString
            urlstr = urlstr.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
            let URL = NSURL(string: urlstr as String)
            if URL == nil{
                print("xzimageview  无效的图片地址")
                return
            }
            let request = NSMutableURLRequest(URL:URL!)
            request.timeoutInterval = 20.0
            let downloadTask = session.downloadTaskWithRequest(request)
            downloadTask.taskDescription = existAndPath.1
            downloadTask.resume()
        }
    }
}
extension UIImageView{
    func addColorAtCornerWithColor(color:UIColor){
        let offset:CGFloat = 15.0
        let shapeLayer = CAShapeLayer()
        shapeLayer.frame = self.bounds
        shapeLayer.fillColor = UIColor.clearColor().CGColor
        shapeLayer.strokeColor = color.CGColor
        shapeLayer.lineWidth = 2.0
        shapeLayer.lineJoin = "round"
        let path = UIBezierPath()
        path.moveToPoint(self.bounds.origin)
        path.addLineToPoint(CGPointMake(shapeLayer.bounds.origin.x, offset))
        path.moveToPoint(shapeLayer.bounds.origin)
        path.addLineToPoint(CGPointMake(offset, shapeLayer.bounds.origin.y))
        
        path.moveToPoint(CGPointMake(shapeLayer.bounds.size.width, shapeLayer.bounds.origin.y))
        path.addLineToPoint(CGPointMake(shapeLayer.bounds.size.width-offset, shapeLayer.bounds.origin.y))
        path.moveToPoint(CGPointMake(shapeLayer.bounds.size.width, shapeLayer.bounds.origin.y))
        path.addLineToPoint(CGPointMake(shapeLayer.bounds.size.width, shapeLayer.bounds.origin.y+offset))
        
        path.moveToPoint(CGPointMake(shapeLayer.bounds.origin.x, shapeLayer.bounds.size.height))
        path.addLineToPoint(CGPointMake(shapeLayer.bounds.origin.x, shapeLayer.bounds.size.height-offset))
        path.moveToPoint(CGPointMake(shapeLayer.bounds.origin.x, shapeLayer.bounds.size.height))
        path.addLineToPoint(CGPointMake(shapeLayer.bounds.origin.x+offset, shapeLayer.bounds.size.height))
        
        path.moveToPoint(CGPointMake(shapeLayer.bounds.size.width, shapeLayer.bounds.size.height))
        path.addLineToPoint(CGPointMake(shapeLayer.bounds.size.width - offset, shapeLayer.bounds.size.height))
        path.moveToPoint(CGPointMake(shapeLayer.bounds.size.width, shapeLayer.bounds.size.height))
        path.addLineToPoint(CGPointMake(shapeLayer.bounds.size.width, shapeLayer.bounds.size.height-offset))
        
        
        shapeLayer.path = path.CGPath
        self.layer.addSublayer(shapeLayer)
    }
}
class TapImageView: XZImageView {
    var TapCompelete:((id:String?)->Void)?
    var id:String = ""
    override init(frame: CGRect) {
        super.init(frame: frame)
        userInteractionEnabled = true
        let g = UITapGestureRecognizer(target: self, action: "didTap:")
        self.addGestureRecognizer(g)
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    func didTap(g:UIGestureRecognizer){
        TapCompelete?(id:self.id)
    }
//    override func  touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
//        TapCompelete?(id:self.id)
//    }
}
public let imageCache = "imageCache"
public let orderCache = "orderCache"
class Common{
    private struct DirectoryType{
        static var cachePath:String?
        static var documentPath:String?
    }
    static func imageFileExistInCache(imageUrl:NSString)->(Bool,String){
        var nameWithUrl = imageUrl.stringByReplacingOccurrencesOfString("//", withString:"_")
        nameWithUrl = nameWithUrl.stringByReplacingOccurrencesOfString("/", withString:"_")
        nameWithUrl = nameWithUrl.stringByReplacingOccurrencesOfString(".", withString:"_")
        nameWithUrl = nameWithUrl.stringByReplacingOccurrencesOfString(":", withString:"_")
        let imagePath = Common.imageCacheDirectory+"/"+nameWithUrl
        return (NSFileManager.defaultManager().fileExistsAtPath(imagePath),imagePath)
    }
    static func cartObjectFileExist(fileName:String)->(Bool,String){
        let path = Common.plistDocumentDirectory+"/"+fileName
        return (NSFileManager.defaultManager().fileExistsAtPath(path),path)
    }
    class var imageCacheDirectory:String{
        if(DirectoryType.cachePath != nil){
            return DirectoryType.cachePath!
        }
        let cachePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] 
        let imageDirectoyPath = cachePath+"/"+imageCache
        var isDir = ObjCBool(false)
        let isExist = NSFileManager.defaultManager().fileExistsAtPath(imageDirectoyPath, isDirectory: &isDir)
        if((!isExist)||(!isDir)){
            do {
                try NSFileManager.defaultManager().createDirectoryAtPath(imageDirectoyPath, withIntermediateDirectories: true, attributes: nil)
            } catch _ {
            }
        }
        DirectoryType.cachePath = imageDirectoyPath
        return imageDirectoyPath
    }
    class var plistDocumentDirectory:String{
        if DirectoryType.documentPath != nil{
            return DirectoryType.documentPath!
        }
        let cachePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] 
        let orderPath = cachePath+"/"+orderCache
        var isDir = ObjCBool(false)
        let isExist = NSFileManager.defaultManager().fileExistsAtPath(orderPath, isDirectory: &isDir)
        if((!isExist)||(!isDir)){
            do {
                try NSFileManager.defaultManager().createDirectoryAtPath(orderPath, withIntermediateDirectories: true, attributes: nil)
            } catch _ {
            }
        }
        DirectoryType.documentPath = orderPath
        return orderPath
    }
}

